package com.example.a22310.myapplication.ViewModel.User;


import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import com.example.a22310.myapplication.Activity.CheckPhoneNumber;
import com.example.a22310.myapplication.Activity.MainActivity;
import com.example.a22310.myapplication.Beans.user;
import com.example.a22310.myapplication.Listener.UserListener;
import com.example.a22310.myapplication.Model.UserModel;
import com.example.a22310.myapplication.databinding.ActivityLoginBinding;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static android.content.Context.MODE_PRIVATE;

public class LoginViewModel implements UserListener {
    private ActivityLoginBinding activityLoginBinding;
    private AppCompatActivity activity;

    private String phone;
    private String password;
    private user user = new user();

    private SharedPreferences sharedPreferences;
    private SharedPreferences.Editor editor;
    private String FILENAME = "yuejian'data";


    private UserLoginTask mAuthTask = null;

    public LoginViewModel(AppCompatActivity activity, ActivityBinding activityLoginBinding) {
        this.activity = activity;
        this.activityLoginBinding = activityLoginBinding;
        Initialize();
        activityLoginBinding.setModel(this);
    }

    public void button_commit_login(View view) {  //登录
        attemptLogin();
    }

    private void Initialize() {
        Intent intent =activity.getIntent();
        activityLoginBinding.phoneNumber.setText(intent.getStringExtra("phone"));
        activityLoginBinding.password.setText(intent.getStringExtra("pwd"));
        sharedPreferences = activity.getSharedPreferences(FILENAME, MODE_PRIVATE);
        editor = sharedPreferences.edit();

        boolean isRemember = sharedPreferences.getBoolean("remember_password", false);
        if (isRemember) {
            String account = sharedPreferences.getString("account", "");
            String password = sharedPreferences.getString("password", "");
            activityLoginBinding.phoneNumber.setText(account);
            activityLoginBinding.password.setText(password);
            activityLoginBinding.remenberPassword.setChecked(true);
        }
    }

    public void forgetPassword(View view) {  //跳到忘记密码
        Intent intent = new Intent();
        intent.setClass(activity, CheckPhoneNumber.class);
        Bundle bundle = new Bundle();
        bundle.putInt("flag",1);
        intent.putExtras(bundle);
        activity.startActivity(intent);
    }

    public void textView_register(View view) {  //跳到注册页面
        Intent intent = new Intent();
        intent.setClass(activity, CheckPhoneNumber.class);
        Bundle bundle = new Bundle();
        bundle.putInt("flag",0);
        intent.putExtras(bundle);
        activity.startActivity(intent);
    }

    public void qqlogin(View view) {  //qq第三方登录
        new QQTencent(activity).qqLogin();
    }

    /*
    实现获取用户登录接口
     */
    @Override
    public void onSuccess(user user) {
        if (0 != user.getUid()) {

            utf_8();//把乱码转换为数字

            if (activityLoginBinding.remenberPassword.isChecked()) {
                editor.putBoolean("remember_password", true);
                editor.putString("account", phone);
                editor.putString("password", password);
            } else {
                editor.clear();     //如果第二次没有点击记住密码，则在登录后忘记密码和账号
            }
            Intent intent = new Intent(activity, MainActivity.class);
            activity.startActivity(intent);
            editor.putInt("userId",user.getUid());
            editor.commit();  //如果登录成功，就保存数据到sharedPreferences中
            activity.finish();
        } else {
            editor.clear();  //如果登录失败，则清除sharedPreferences中的数据
            editor.commit();
            Toast.makeText(activity, "用户名或密码错误", Toast.LENGTH_LONG).show();
        }
    }



    @Override
    public void onSuccess(UserModel user) {

    }

    @Override
    public void onFailure() {

    }



//    对手机号和密码检测

    public void attemptLogin() {

        utf_8();//把乱码转换为数字


        if (mAuthTask != null) {
            return;
        }

        // Reset errors.
        activityLoginBinding.phoneNumber.setError(null);
        activityLoginBinding.password.setError(null);


        boolean cancel = false;
        View focusView = null;

        if (TextUtils.isEmpty(password)){
            activityLoginBinding.password.setError("密码不能为空");
            focusView = activityLoginBinding.password;
            cancel = true;
        } else if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
            activityLoginBinding.password.setError("密码位数太少");
            focusView = activityLoginBinding.password;
            cancel = true;
        }

        // Check for a valid email address.
        Pattern p = Pattern.compile("[0-9]*");
        Matcher m = p.matcher(phone);

        if (!TextUtils.isEmpty(phone)) {
            if (isInteger(phone)) {
                activityLoginBinding.phoneNumber.setError("这不是一个合法的手机号");
                focusView = activityLoginBinding.phoneNumber;
                cancel = true;
            }

            if (11!=isPhoneNumber(phone)) {
                activityLoginBinding.phoneNumber.setError("请输入11为手机号");
                focusView = activityLoginBinding.phoneNumber;
                cancel = true;
            }

        }
        else {
            activityLoginBinding.phoneNumber.setError("手机号必填");
            focusView = activityLoginBinding.phoneNumber;
            cancel = true;
        }

        if (cancel) {
            // There was an error; don't attempt login and focus the first
            // form field with an error.
            focusView.requestFocus();
        } else {
            mAuthTask = new UserLoginTask(phone, password);
            mAuthTask.execute((Void) null);
            //登录检测
            user.setUser_user(phone);
            user.setUser_password(password);

            UserModel userModel=new UserModel();
            userModel.login(user,LoginViewModel.this);
        }
    }

    private int isPhoneNumber(String phone) {

        return  phone.length();
    }

    private boolean isPasswordValid(String password) {
        //TODO: Replace this with your own logic
        return password.length() > 5;
    }



    /**
     * Represents an asynchronous login/registration task used to authenticate
     * the user.
     */
    public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {

        private final String mPhone;
        private final String mPassword;

        UserLoginTask(String phoneNum, String password) {
            mPhone = phoneNum;
            mPassword = password;
        }

        @Override
        protected Boolean doInBackground(Void... params) {
            // TODO: attempt authentication against a network service.

            try {
                // Simulate network access.
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                return false;
            }


            // TODO: register the new account here.
            return true;
        }

        @Override
        protected void onPostExecute(final Boolean success) {
            mAuthTask = null;

            if (success) {
                // finish();
            } else {
                activityLoginBinding.password.setError("密码错误");
                activityLoginBinding.password.requestFocus();
            }
        }

        @Override
        protected void onCancelled() {
            mAuthTask = null;
        }
    }
    public static boolean isInteger(String value) {
        try {
            Integer.parseInt(value);
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }
    //根据用户手机号获取用户头像
    private void setUserPic(){
        if(""!=user.getUser_user()){
            user.setUser_user(activityLoginBinding.phoneNumber.getText().toString());
            UserModel userModel=new UserModel();
            userModel.acquireUserPic(user,LoginViewModel.this);
        }else {
            activityLoginBinding.userPic.setVisibility(View.GONE);
        }

    }

    private void utf_8(){
        try {
            phone =  URLEncoder.encode(activityLoginBinding.phoneNumber.getText().toString(),
                    "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        try {
            password =  URLEncoder.encode(activityLoginBinding.password.getText().toString(),
                    "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

}